<template>
	<view class="login-container">
		<view class="form-container">
			<text class="login-title">登入</text>

			<view class="input-group">
				<wd-input type="text" v-model="form.username" placeholder="请输入用户名" clearable />
			</view>

			<view class="input-group">
				<wd-input type="password" v-model="form.password" placeholder="请输入密码" show-password clearable />
			</view>

			<view class="btn-row">
				<wd-button class="login-btn" type="primary" :loading="loading" @click="handleLogin">登录</wd-button>
				<text class="register-link" @click="goRegister">去注册</text>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { request, BASE_URL } from '@/Requset/request'

const form = reactive({
    username: '',
    password: ''
})

const loading = ref(false)

let redirect = ''
let id = ''
onLoad((options) => {
  redirect = options.redirect || ''
  id = options.id || ''
})

async function handleLogin() {
    if (!form.username.trim()) {
        uni.showToast({ title: '请输入用户名', icon: 'none' })
        return
    }

    if (!form.password) {
        uni.showToast({ title: '请输入密码', icon: 'none' })
        return
    }

    loading.value = true

    try {
        const response = await request({
            url: BASE_URL + 'api/login',
            method: 'POST',
            data: {
                username: form.username,
                password: form.password
            },
            header: {
                'Content-Type': 'application/json'
            }
        })

        const res = (response as any).data

        if (!res) {
            throw new Error('无效的响应数据')
        }

        if (res.status === 0) {
            uni.setStorageSync('token', res.token)
            uni.setStorageSync('refreshToken', res.refreshToken)
            uni.setStorageSync('userInfo', JSON.stringify(res.userInfo || {}))
            uni.setStorageSync('loginTime', Date.now())

            // 获取 openid 并存储
            uni.login({
                provider: 'weixin',
                success: async (loginRes) => {
                    if (loginRes.code) {
                        try {
                            const openidRes = await request({
                                url: BASE_URL + 'api/getopenid',
                                method: 'POST',
                                header: { 'content-type': 'application/x-www-form-urlencoded' },
                                data: { code: loginRes.code }
                            })
                            console.log('getopenid 返回:', openidRes)
                            if (openidRes.data && openidRes.data.openid) {
                                uni.setStorageSync('openid', openidRes.data.openid)
                                console.log('openid 获取成功:', openidRes.data.openid)
                                uni.showToast({
                                    title: res.message || '登录成功',
                                    icon: 'success'
                                })
                                setTimeout(() => {
                                  if (redirect === 'detail' && id) {
                                    uni.reLaunch({ url: `/pages/detail/detail?id=${id}` })
                                  } else {
                                    uni.navigateBack()
                                  }
                                }, 1000)
                            } else {
                                console.warn('openid 获取失败:', openidRes)
                                uni.showToast({
                                    title: 'openid获取失败，请重试',
                                    icon: 'none'
                                })
                            }
                        } catch (e) {
                            console.error('获取 openid 失败:', e)
                            uni.showToast({
                                title: 'openid获取失败，请重试',
                                icon: 'none'
                            })
                        }
                    }
                },
                fail: (err) => {
                    console.error('uni.login 失败:', err)
                    uni.showToast({
                        title: '微信登录失败',
                        icon: 'none'
                    })
                }
            })
        } else {
            uni.showToast({
                title: res.message || '登录失败',
                icon: 'none',
                duration: 3000
            })
        }
    } catch (error: any) {
        console.error('登录请求失败:', error)
        uni.showToast({
            title: error.message || '请求失败，请检查网络',
            icon: 'none',
            duration: 3000
        })
    } finally {
        loading.value = false
    }
}

function goRegister() {
  uni.navigateTo({
    url: '/pages/register/register'
  })
}
</script>

<style scoped>
	.login-container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		background-color: #f5f5f5;
		padding: 40rpx;
	}

	.form-container {
		width: 100%;
		max-width: 600rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 60rpx 40rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
	}

	.login-title {
		display: block;
		text-align: center;
		font-size: 40rpx;
		font-weight: bold;
		margin-bottom: 60rpx;
		color: #333;
	}

	.input-group {
		margin-bottom: 40rpx;
	}

	.input-item {
		border: 1px solid #dcdfe6;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 32rpx;
	}

	.btn-row {
		display: flex;
		justify-content: space-between; /* 两端对齐 */
		align-items: center;
		margin-top: 30rpx;
		width: 100%;
	}

	.login-btn {
		width: 200rpx;
		height: 88rpx;
		font-size: 34rpx;
		border-radius: 44rpx;
	}

	.register-link {
		color: #999;
		font-size: 26rpx;
		cursor: pointer;
	}
</style>